package mysql

import (
	"WebSvr/modules/common"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"

	_ "github.com/go-sql-driver/mysql"
)

type ServerCfg struct {
	Id        int    `orm:"auto"`
	Ip        string `orm:"size(100)"`
	Port      int
	Name      string `orm:"size(100)"`
	Area      string `orm:"size(100)"`
	ChannelId string `orm:"size(100)"`
	NewServer uint8
}

type PcStatus struct {
	Id           int    `orm:"auto"`
	Name         string `orm:"size(100)"`
	Time         string `orm:"size(100)"`
	CpuUsage     float64
	MemSysUsage  uint64
	MemProgUsage uint64
	TotalMem     uint64
}

type UserCfg struct {
	Id     int    `orm:"auto"`
	Name   string `orm:"size(100)"`
	Ip     string `orm:"size(100)"`
	Passwd string `orm:"size(100)"`
	Access int
	Other  string `orm:"size(100)"`
}

type AnnounceData struct {
	Id       int    `orm:"auto"`
	Announce string `orm:"size(100)"`
	Time     string `orm:"size(100)"`
}

func Initmysql() {
	//webAdmin ini
	dbhost_webAdmin := beego.AppConfig.String("dbhost_webAdmin")
	dbport_webAdmin := beego.AppConfig.String("dbport_webAdmin")
	dbuser_webAdmin := beego.AppConfig.String("dbuser_webAdmin")
	dbpasswd_webAdmin := beego.AppConfig.String("dbpasswd_webAdmin")
	dbname_webAdmin := beego.AppConfig.String("dbname_webAdmin")
	dburl_webAdmin := dbuser_webAdmin + ":" + dbpasswd_webAdmin + "@tcp(" + dbhost_webAdmin + ":" + dbport_webAdmin + ")/" + dbname_webAdmin + "?charset=utf8"

	//Report_mysql ini
	dbhost_Report := beego.AppConfig.String("dbhost_Report")
	dbport_Report := beego.AppConfig.String("dbport_Report")
	dbuser_Report := beego.AppConfig.String("dbuser_Report")
	dbpasswd_Report := beego.AppConfig.String("dbpasswd_Report")
	dbname_Report := beego.AppConfig.String("dbname_Report")
	dburl_Report := dbuser_Report + ":" + dbpasswd_Report + "@tcp(" + dbhost_Report + ":" + dbport_Report + ")/" + dbname_Report + "?charset=utf8"

	orm.RegisterModel(new(ServerCfg))
	orm.RegisterModel(new(UserCfg))
	orm.RegisterModel(new(AnnounceData))
	orm.RegisterDataBase(common.ALIAS_WEBADMIN, "mysql", dburl_webAdmin)
	orm.RegisterModel(new(PcStatus))
	orm.RegisterDataBase(common.ALIAS_DATAREPORT, "mysql", dburl_Report)

	//init mysql
	newWebAdmin()
	gWebAdmin.LoadSql()
	gWebAdmin.LoadAllUserInfo()
	gWebAdmin.LoadAnnounceSql()
	admin_defName := beego.AppConfig.String("name")
	admin_defPasswd := beego.AppConfig.String("passwd")
	admin_defIp := beego.AppConfig.String("bindip")
	if admin_defIp == "localhost" {
		admin_defIp = "127.0.0.1"
	}
	bsucc, errDefault := gWebAdmin.InsertDefaultAdmin(admin_defName, admin_defPasswd, admin_defIp)
	if !bsucc {
		beego.Error("InsertDefaultAdmin err:%v", errDefault)
	}

	NewPcStatus()
}
